/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.adv.web.intercepter;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.util.StringUtils;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.adv.web.common.OAuthRequired;
import com.adv.web.service.BaseService;

/**
 * 微信企业号获取userid
 * 
 * @author zhouxin
 * @date 2017年4月19日
 * @version v1.0
 */
public class WeiXinInterceptor  extends BaseService implements
		HandlerInterceptor {

	@Autowired
	private WxMpService wxMpService;

	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		return true;
	}

	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		if (handler instanceof HandlerMethod) {
			HandlerMethod method = (HandlerMethod) handler;
			OAuthRequired needVerify = method.getMethodAnnotation(OAuthRequired.class);
			ServletContext ctx = request.getSession().getServletContext();
			if (needVerify != null) {
				    String userId =(String)ctx.getAttribute("userId");
				    if (StringUtils.isBlank(userId)) {
				        String code = request.getParameter("code");
						if(StringUtils.isNotBlank(code)){
							WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
							WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
							ctx.setAttribute("userId", wxMpUser.getOpenId());
							wxMpOAuth2AccessToken = wxMpService.oauth2refreshAccessToken(wxMpOAuth2AccessToken.getRefreshToken());
						}else {
							String resultUrl = request.getRequestURL().toString();
							String param = request.getQueryString();
							if (param!=null) {
								resultUrl+="?" + param;
							}
							String url = wxMpService.oauth2buildAuthorizationUrl(resultUrl,WxConsts.OAUTH2_SCOPE_USER_INFO, null);
							response.sendRedirect(url);
						}
				    }
			}
		}
	}

	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
	}


}
